package com.aijia.custom.product.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aijia.custom.product.R;
import com.aijia.custom.product.adapter.NoScrollGridAdapter;
import com.aijia.custom.product.adapter.RecordAdapter;
import com.aijia.custom.product.customview.CanDoBlankGridView;
import com.aijia.custom.product.customview.LoadingWaitDialog;
import com.aijia.custom.product.customview.MyListView;
import com.aijia.custom.product.customview.NoDoubleClickListener;
import com.aijia.custom.product.data.ProcessData;
import com.aijia.custom.product.data.SheetData;
import com.aijia.custom.product.data.WSheetRecListData;
import com.aijia.custom.product.listener.IWSheetRecAddListener;
import com.aijia.custom.product.listener.IWSheetRecListListener;
import com.aijia.custom.product.manager.WSheetRecAddManager;
import com.aijia.custom.product.manager.WSheetRecListManager;
import com.aijia.custom.product.utils.AddOrderHelper;
import com.aijia.custom.product.utils.ArtStatusHelper;
import com.aijia.custom.product.utils.Notification;
import com.aijia.custom.product.utils.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yejianjun on 2019/4/23.
 */

public class OrderItemActivity extends Activity implements ArtStatusHelper.IArtStatusListener, IWSheetRecListListener, IWSheetRecAddListener, RecordAdapter.OnItemClickListener, AddOrderHelper.IDataChangerListener {
    // 店铺名
    private TextView shopNameTV;
    // 产品
    private TextView customerTV;
    // 发起人
    private TextView orginatorTV;
    // 时间
    private TextView createDateTV;
    // 名称
    private TextView nameTV;
    // 旺旺ID
    private TextView wwIdTV;
    // 微信
    private TextView wechatTV;
    // 电话
    private TextView mobileTV;
    // 地址
    private TextView addressTV;
    // 备注
    private TextView contentTV;

    private TextView titleTV;
    private ImageButton rightBtn, backBtn;

    private CanDoBlankGridView gridview;
    private ScrollView mScrollView;

    private NoScrollGridAdapter adapter;
    private ArrayList<ProcessData> itemList = new ArrayList<>();
    private SheetData sheetData;
    private WSheetRecListManager manager;
    private TextView addRecTV;
    private WSheetRecAddManager addManager;

    private Dialog pDialog;
    private Dialog customDialog;
    private MyListView listView;
    private RecordAdapter recordAdapter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actiity_order_item_detail);
        init();
        initData();
        initManager();
        reqData();

    }

    private void init() {
        initTitle();
        initInclude();
        gridview = findViewById(R.id.oder_item_gridview);
        mScrollView = findViewById(R.id.order_item_detail_scroll);

        listView = findViewById(R.id.contact_record_list);
        recordAdapter = new RecordAdapter(this, 1);
//        recordAdapter.setOnItemClickListener(this);
        listView.setAdapter(recordAdapter);
    }

    private void initTitle() {
        titleTV = findViewById(R.id.title_tv);
        rightBtn = findViewById(R.id.right_imageButton);
        backBtn = findViewById(R.id.left_imageButton);
        addRecTV = findViewById(R.id.right_text_tv);
        backBtn.setVisibility(View.VISIBLE);
        addRecTV.setVisibility(View.GONE);
        rightBtn.setVisibility(View.VISIBLE);
        titleTV.setText("订单详情");
//        addRecTV.setText("添加记录");
        rightBtn.setOnClickListener(noDoubleClickListener);
        backBtn.setOnClickListener(noDoubleClickListener);
        addRecTV.setOnClickListener(noDoubleClickListener);
    }

    private void initInclude() {
        shopNameTV = findViewById(R.id.order_item_shopName);
        customerTV = findViewById(R.id.order_item_customer);
        orginatorTV = findViewById(R.id.order_item_originator);
        createDateTV = findViewById(R.id.order_item_createtime);
        nameTV = findViewById(R.id.order_item_name);
        wwIdTV = findViewById(R.id.order_item_wwId);
        wechatTV = findViewById(R.id.order_item_wechat);
        mobileTV = findViewById(R.id.order_item_mobile);
        addressTV = findViewById(R.id.order_item_address);
        contentTV = findViewById(R.id.order_item_content);
    }

    private void initData() {
        itemList = getIntent().getParcelableArrayListExtra("items");
        sheetData = getIntent().getParcelableExtra("sheetData");

        display();

        adapter = new NoScrollGridAdapter(this, itemList);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new MyItemClickListener(sheetData.getId(), itemList));
        gridview.post(new Runnable() {
            @Override
            public void run() {
                mScrollView.scrollTo(0, 0);
            }
        });
    }

    private void initManager() {
        manager = new WSheetRecListManager(this);
        manager.addWSheetRecListListener(this);
        addManager = new WSheetRecAddManager(this);
        addManager.addWSheetRecAddListener(this);
        AddOrderHelper.getInstance().addListener(this);
        ArtStatusHelper.getInstance().addListener(this);
    }

    private void reqData() {
        manager.wSheetRecList(sheetData.getId());
    }

    private void display() {
        shopNameTV.setText("店铺名：" + (sheetData.getShopName() == null ? "" : sheetData.getShopName()));
        customerTV.setText("产品：" + (sheetData.getProductName() == null ? "" : sheetData.getProductName()));
        orginatorTV.setText("发起人：" + (sheetData.getStaffName() == null ? "" : sheetData.getStaffName()));
        createDateTV.setText("日期：" + (sheetData.getUnderDate() == null ? "" : sheetData.getUnderDate()));
        nameTV.setText("名称：" + (sheetData.getName() == null ? "" : sheetData.getName()));
        wwIdTV.setText("旺旺ID：" + (sheetData.getWwId() == null ? "" : sheetData.getWwId()));
        wechatTV.setText("微信：" + (sheetData.getWx() == null ? "" : sheetData.getWx()));
        mobileTV.setText("电话：" + (sheetData.getMobile() == null ? "" : sheetData.getMobile()));
        addressTV.setText("地址：" + (sheetData.getAddress() == null ? "" : sheetData.getAddress()));
        contentTV.setText("备注：" + (sheetData.getContent() == null ? "" : sheetData.getContent()));
    }

    @Override
    public void updateStatus(int wsheetId, int artId, int status, String finishDate) {
        for (int i = 0; i < itemList.size(); i++) {
            if (itemList.get(i).getId() == artId) {
                itemList.get(i).setStatus(status);
                itemList.get(i).setFinishDate(finishDate);
                adapter.updateData(artId, status, finishDate);
                break;
            }
        }
    }

    @Override
    public void updateFinishDate(int wsheetId, String finishDate) {

    }

    @Override
    public void updateRemark(int wsheetId, String content) {

    }

    @Override
    public void updateListStatus(int wsheetId, int status) {

    }

    @Override
    public void onWSheetRecListFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onWSheetRecListSuccess(List<WSheetRecListData> list) {
//        recordAdapter.clear();
        recordAdapter.setData(list);
        recordAdapter.notifyDataSetChanged();
    }

    @Override
    public void onWSheetRecAddFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onWSheetRecAddSuccess() {
        // 新增一条记录成功 刷新一次
        reqData();
    }

    @Override
    public void itemClick(View view) {

    }

    @Override
    public void refreshDate() {

    }

    @Override
    public void updateInfo(SheetData data) {
        sheetData = data;
        display();
    }

    class MyItemClickListener implements AdapterView.OnItemClickListener {

        List<ProcessData> list;
        private int wsheet_id;

        public MyItemClickListener(int id, List<ProcessData> list) {
            wsheet_id = id;
            this.list = list;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent();
            intent.putExtra("wsheet_art_detail_title", list.get(position).getName());
            intent.putExtra("staff_id", list.get(position).getStaffId());
            intent.putExtra("wsheet_id", wsheet_id);
            intent.putExtra("wsheet_art_detail_id", list.get(position).getId());
            intent.setClass(OrderItemActivity.this, WSheetArtDetailActvity.class);
            startActivity(intent);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AddOrderHelper.getInstance().removeListener(this);
        ArtStatusHelper.getInstance().removeListener(this);
        if (null != customDialog && customDialog.isShowing()) {
            customDialog.dismiss();
        }
    }

    private void showDialog() {
        pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
        pDialog.show();
    }

    NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.right_imageButton:
                    showSandianDialog();
                    break;
                case R.id.left_imageButton:
                    finish();
                    break;
                case R.id.right_text_tv:
                    showRecDialog();
                    break;
                default:
                    break;
            }
        }
    };

    private void gouzhaoData() {
        itemList = new ArrayList<>();
        for (int i = 0; i < 9; i++) {
            ProcessData data = new ProcessData();
            data.setId(i);
            data.setName("网店定金");
            data.setStatus(i % 2);
            data.setFinishDate("2019-01-01 00:22:11");
            itemList.add(data);
        }
    }

    private void showRecDialog() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        customDialog = new Dialog(this, R.style.custom_Dialog);
        View layout = inflater.inflate(R.layout.custom_remark_dialog, null);
        final EditText content = layout.findViewById(R.id.complete_remark_et);
        (layout.findViewById(R.id.confirmBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.dismiss();
//                sheetData.setContent(content.getText().toString().trim());
                if (TextUtils.isEmpty(content.getText().toString().trim())) {
                    Notification.toast(OrderItemActivity.this, "内容不能为空");
                    return;
                }
                addManager.wSheetRecAdd(sheetData.getId(), content.getText().toString().trim());
            }
        });
        (layout.findViewById(R.id.cancelBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.dismiss();
            }
        });
        customDialog.setContentView(layout);
        customDialog.show();
    }

    public void showSandianDialog() {
        pDialog = new Dialog(this, R.style.time_dialog);
        pDialog.setCancelable(true);
        pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        View view = LayoutInflater.from(this).inflate(R.layout.sandian_dialog, null);
        TextView dateTV = (TextView) view.findViewById(R.id.btn_modify_date);
        TextView remarkTV = (TextView) view.findViewById(R.id.btn_modify_remark);
        TextView cancelTV = (TextView) view.findViewById(R.id.tv_cancel);

        //修改
        dateTV.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                int userId = SharedPreferencesUtils.getUserID(OrderItemActivity.this);
                // 只用发起人可以修改店铺信息
                if (sheetData.getStaffId() == userId) {
                    Intent intent = new Intent();
                    intent.putExtra("order_item", sheetData);
                    intent.setClass(OrderItemActivity.this, AddOrderActivity.class);
                    startActivity(intent);
                } else {
                    Notification.toast(OrderItemActivity.this, "只有发起人可以修改");
                    return;
                }
            }
        });
        // 添加记录
        remarkTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                showRecDialog();
            }
        });
        // 取消
        cancelTV.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
            }
        });

        pDialog.setContentView(view);
        // 底部显示弹出框 --- 在setContentView之后设置才有效
        Window window = pDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        WindowManager manager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = dm.widthPixels;
        window.setAttributes(lp);
        pDialog.show();
    }

}
